package com.wy.controller.sys;

import com.wy.bean.HouseholdBean;
import com.wy.constants.CommonValues;
import com.wy.model.sys.Households;
import com.wy.model.sys.PageResult;
import com.wy.model.sys.RoleEntity;
import com.wy.model.sys.UserEntity;
import com.wy.service.sys.MenuService;
import com.wy.service.sys.RelationService;
import com.wy.service.sys.RoleService;
import com.wy.service.sys.UserService;
import com.wy.service.wy.HouseholdService;
import com.wy.service.wy.ResidenceService;
import com.wy.utils.BaseResponseInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户管理
 */
@RestController
/*@PreAuthorize("hasRole('ADMI')")*/
@RequestMapping("/users")
@Api(value="API - UserController",description="系统用户管理")
public class UserController {

	private Logger log = LoggerFactory.getLogger(UserController.class);

	@Resource(name = "userServiceImpl")
	private UserService userService;
	@Resource(name = "householdServiceImpl")
	private HouseholdService householdService;
	@Resource(name = "relationServiceImpl")
	private RelationService relationService;
	@Resource(name = "menuServiceImpl")
	private MenuService menuService;
	@Resource(name = "residenceServiceImpl")
	private ResidenceService residenceService;
	@Resource(name = "roleServiceImpl")
	private RoleService roleService;
	@Autowired
	private CommonValues commonValues;

	/**
	 * 根据登录名获取用户详情
	 * @param loginName
	 * @return
	 */
//	@ApiIgnore()
//	@GetMapping("/{loginName}")
//	public UserEntity userGet(@PathVariable String loginName) {
//		UserEntity userEntity = userService.getUserEntityByLoginName(loginName);
//		log.debug("The method is ending");
//		return userEntity;
//	}

	/**
	 * 手机端获取用户信息及权限信息
	 * @param loginName
	 * @return
	 */
	@GetMapping("/{loginName}")
	@ApiOperation(value="userInfoGet",notes="根据用户名获取用户数据及相关")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loginName", value = "登录名称", required = true,dataType = "String", paramType = "query", defaultValue = "")
	})
	public BaseResponseInfo userInfoGet(@PathVariable String loginName) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String, Object> data = new HashMap<String, Object>();
		UserEntity userEntity = userService.getUserEntityByLoginName(loginName);
		List<HouseholdBean> householdBeans = householdService.getHouseHoldByUserId(userEntity.getId());
		List<String>  roleNameList = roleService.getRolesByUserId(userEntity.getId());
		data.put("user",userEntity);
		data.put("householdInfo",householdBeans);
		data.put("roles",roleNameList);
		data.put("webPath",commonValues.getOutsidePath());
		baseResponseInfo.data = data;
		return baseResponseInfo;
	}

	/**
	 * 获取user表数据
	 * @param loginName
	 * @param pageSize
	 * @param page
	 * @return
	 */
	@GetMapping("")
	@ApiOperation(value="usersList",notes="分页获取用户数")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loginName", value = "登录名称", required = true,dataType = "String", paramType = "query", defaultValue = ""),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true,dataType = "int", paramType = "query", defaultValue = ""),
			@ApiImplicitParam(name = "page", value = "当前页数", required = true,dataType = "int", paramType = "query", defaultValue = "")
	})
	public PageResult usersList(String loginName, int pageSize, int page) {
		PageResult pageResult = new PageResult();
		pageResult.setData(userService.usersList(loginName, pageSize, page * pageSize));
		pageResult.setTotalCount(userService.usersSize(loginName, pageSize, page * pageSize));
		log.debug("The method is ending");
		return pageResult;
	}

	/**
	 * 新建用户信息
	 * @param userEntity
	 * @return
	 */
	@PostMapping("/user")
	@ApiOperation(value="insertUser",notes="新建用户")
	public BaseResponseInfo insertUser(@RequestBody UserEntity userEntity) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String,Object> map = new HashMap<>();
		//手机号非空判断
		if(null == userEntity.getMobile()) {
			map.put("message","手机号不能为空！");
			baseResponseInfo.code = 500;
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}
		//手机号唯一判断
		UserEntity userEntityExists = userService.getUserByMobile(userEntity.getMobile());
		if(null != userEntityExists) {
			map.put("message","该手机号已注册，请重新填写！");
			baseResponseInfo.data = map;
			baseResponseInfo.code = 500;
			return baseResponseInfo;
		}

		userEntity.setStatus("1");//默认账户：启用状态
		userEntity.setAuthStatus("1");//web端注册默认：已认证状态
		userEntity.setSource("2");//注册来源：web端
//		userEntity.setLoginName();
		userService.insertUser(userEntity);
		map.put("message","成功");
		baseResponseInfo.data = map;
		return baseResponseInfo;
	}

	/**
	 * 更新用户信息
	 * 
	 * @param userEntity
	 * @param id
	 * @return
	 */
	@PutMapping("/{id}")
	@ApiOperation(value="updateUser",notes="更新用户信息")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "用户id", required = true,dataType = "int", paramType = "query", defaultValue = "")
	})
	public BaseResponseInfo updateUser(@RequestBody UserEntity userEntity, @PathVariable int id) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String,Object> map = new HashMap<>();
		if (userEntity.getId() == id) {
			//手机号非空判断
			if(null == userEntity.getMobile()) {
				map.put("message","手机号不能为空！");
				baseResponseInfo.data = map;
				return baseResponseInfo;
			}

			//手机号唯一判断
			UserEntity userEntityExists = userService.getUserByMobile(userEntity.getMobile());
			if(null != userEntityExists && userEntityExists.getId() != id) { //手机号码存在且用户id不等于id则说明其他用户注册
				map.put("message","该手机号已注册，请重新填写！");
				baseResponseInfo.data = map;
				return baseResponseInfo;
			}

			userService.updateUser(userEntity);
		}else{
			map.put("message","数据异常！");
			baseResponseInfo.data = map;
			return baseResponseInfo;
		}
		return baseResponseInfo;
	}

	/**
	 * 删除用户信息
	 * 
	 * @param groupId
	 * @return
	 */
	@DeleteMapping("")
	@ApiOperation(value="deleteUsers",notes="删除用户")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "groupId", value = "用户数组", required = true,dataType = "array", defaultValue = "")
	})
	public List<String> deleteUsers(@RequestBody List<String> groupId) {
		userService.deleteUsers(groupId);
		return groupId;
	}


	/**
	 * 手机端注册,根据用户注册的类型
	 * @param loginName 手机号码，全局唯一
	 * @param password 密码
	 * @param houseId 房屋id
	 * @return
	 */
	@PostMapping("/register")
	@ApiOperation(value="registerStep1",notes="手机端注册用户")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loginName", value = "登录名", required = true,dataType = "String", defaultValue = ""),
			@ApiImplicitParam(name = "password", value = "登录密码", required = true,dataType = "String", defaultValue = ""),
			@ApiImplicitParam(name = "houseId", value = "房屋id", required = true,dataType = "String", defaultValue = "")
	})
	public BaseResponseInfo registerStep1(@RequestParam(value="loginName",required=false) String loginName,
										  @RequestParam(value="password",required=false) String password,
										  @RequestParam(value="houseId") Integer houseId){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		Map<String,String> result = new HashMap<String,String>();
		//检查数据
		if(StringUtils.isEmpty(loginName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(houseId)){
			baseResponseInfo.code = 500;
			result.put("message","参数不能为空");
			baseResponseInfo.data = result;
			return baseResponseInfo;
		}

		try {
			baseResponseInfo.data = userService.register(loginName, password, houseId);
		}catch (Exception ex) {
			baseResponseInfo.code = 500;
			result.put("message","注册异常");
			baseResponseInfo.data = result;
		}
		return baseResponseInfo;
	}


//	/**
//	 * 我有多套房
//	 * @param uid 用户id
//	 * @param houseId 新房屋id
//	 * @return
//	 */
//	@PostMapping("/addNewHouse")
//	@ApiOperation(value="addNewHouse",notes="手机端添加其他房屋信息")
//	public BaseResponseInfo addNewHouse(
//			@RequestParam(value="uid") Integer uid,
//			@RequestParam(value="houseId") Integer houseId) {
//		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
//		Map<String,Object> result = new HashMap<>();
//		//判断数据合法性
//		if(null != uid && null != houseId) {
//			baseResponseInfo.code = 500;
//			result.put("message","参数不能为空");
//			baseResponseInfo.data = result;
//			return baseResponseInfo;
//		}
//		//根据用户id和房屋id判断是否已经注册
//		Households householdExists = householdService.getHouseholdByUidAndHid(uid,houseId);
//		if(null != householdExists) {
//			baseResponseInfo.code = 500;
//			result.put("message","用户已注册过该房屋，请重新选择");
//			baseResponseInfo.data = result;
//			return baseResponseInfo;
//		}
//		//根据用户id获取用户信息
//		UserEntity currentUser = userService.getUserById(uid);
//		//添加住户信息
//		Households householdEntity = new Households();
//		householdEntity.setUserId(uid);//用户id
//		householdEntity.setHouseId(houseId);//房屋id
//		householdEntity.setMobile(currentUser.getMobile());//手机号码
//		householdEntity.setStatus("1");//0禁用，1启用
//		householdEntity.setAuthStatus("0");//0未认证,1已认证
//		householdEntity.setCreateTime(new Date());
//		householdService.insertHousehold(householdEntity);
//
//		return baseResponseInfo;
//	}

	/**
	 * 修改密码
	 * @param loginName
	 * @param newPassword
	 * @param oldPassword
	 * @return
	 */
	@PostMapping("/modifyPassword")
	@ApiOperation(value="modifyPassword",notes="修改密码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "loginName", value = "登录名", required = true,dataType = "String", defaultValue = ""),
			@ApiImplicitParam(name = "oldPassword", value = "旧密码", required = true,dataType = "String", defaultValue = ""),
			@ApiImplicitParam(name = "newPassword", value = "新密码", required = true,dataType = "String", defaultValue = "")
	})
	public BaseResponseInfo modifyPassword(String loginName,String newPassword,String oldPassword){
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		int flag = userService.modifyPasswordValidate(newPassword,oldPassword,loginName);
		baseResponseInfo.code = flag;
		return baseResponseInfo;
	}

	@GetMapping("/getMaintenanceList")
	@ApiOperation(value="getMaintenanceList",notes="获取小区维修人员列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "residenceId", value = "小区ID", required = true,dataType = "int", defaultValue = "")
	})
	public BaseResponseInfo getMaintenanceList(Integer residenceId) {
		BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
		baseResponseInfo.data = userService.getMaintenanceList(residenceId);
		return baseResponseInfo;
	}

}
